package com.sy.cloud.guess.controller;

import com.alibaba.fastjson.JSONObject;
import com.sy.cloud.guess.model.Chestlist;
import com.sy.cloud.guess.model.Chestlist2;
import com.sy.cloud.guess.model.KnaHistory;
import com.sy.common.model.Juejinuser;
import com.sy.common.service.IBaseService;
import com.sy.common.service.IDbService;
import com.sy.common.service.ITestService;
import com.sy.shiro.UsernameToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mac on 2018/1/22.
 */
@Controller
@Slf4j
@RequestMapping("/integral")
public class IntegralController {

    @Resource
    private IDbService dbService;
    @Resource
    private ITestService testService;

    @Resource
    private IBaseService baseService;

    /**
     * 奖券寻宝列表
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "chestList", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject chestList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        List<Chestlist> chestlistList = baseService.listQuery("From Chestlist", Chestlist.class);

        UsernameToken utoken = testService.getUser();
        List<Chestlist2> chestlist2List = new ArrayList<Chestlist2>();
        if (utoken != null) {
            // 把宝箱收否可以领取的信息也返回
            Juejinuser juejinuser = testService.getJueUserById(utoken.getUserId().toString());
            if (juejinuser != null) {
                Integer chestId = juejinuser.getChestId();
                if (chestId != null) {
                    for (int i = 0; i < chestlistList.size(); i++) {
                        Chestlist2 chestlist2 = new Chestlist2();
                        chestlist2.setId( chestlistList.get(i).getId() );
                        chestlist2.setCoin(chestlistList.get(i).getCoin());
                        chestlist2.setImg(chestlistList.get(i).getImg());
                        chestlist2.setTicket(chestlistList.get(i).getTicket());
                        chestlist2.setEnable(1);// 显示为灰色

                        if (i < chestId) {
                            chestlist2.setEnable(0);// 显示为已点
                        }
                        chestlist2List.add(chestlist2);
                    }
                }
            }
        }else{
            result.put("status", "0");
            result.put("message", "没有登录");
            return result;
        }

        result.put("status", "1");
        result.put("message", chestlist2List);
        return result;
    }


    /**
     * 奖券寻宝兑换ticket
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "chestExchange", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JSONObject chestExchange(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();

        UsernameToken utoken = testService.getUser();
        if (utoken == null) {
            result.put("status", "0");
            result.put("message", "没有登录");
            return result;
        }

        Juejinuser juejinuser = testService.getJueUserById(utoken.getUserId().toString());
        if (juejinuser == null) {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            result.put("status", "0");
            result.put("message", "没有登录");
            return result;
        }

        String chestId = request.getParameter("chestId");
        log.info("传入的chestId是"+chestId);
        if (chestId == null) {
            result.put("status", "0");
            result.put("message", "chestId参数必传");
            return result;
        }
        Integer pchestId = Integer.parseInt(chestId);

        Integer uchid = juejinuser.getChestId();
        if (pchestId <= uchid) {
            result.put("status", "0");
            result.put("message", "已领取过的宝箱不可以再领取");
            return result;
        }

        if (pchestId > uchid + 1) {
            result.put("status", "0");
            result.put("message", "请先领取下层宝箱");
            return result;
        }

        if (testService.exchangeTicket(juejinuser, pchestId)) {
            result.put("status", "1");
            result.put("message", "success");
        } else {
            result.put("status", "0");
            result.put("message", "奖券不足");
        }
        return result;
    }


    /**
     * 集齐9张英雄卡时获得奖励
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "KnapsackHeroOpen", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JSONObject KnapsackHeroOpen(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        UsernameToken utoken = testService.getUser();
        Juejinuser juejinuser = new Juejinuser();
        if( utoken != null ){
            juejinuser = testService.getJueUserById( utoken.getUserId().toString() );
            if( juejinuser == null ){
                Subject subject = SecurityUtils.getSubject();
                subject.logout();
            }
        }
        utoken = testService.getUser();
        if( utoken == null ){
            result.put("status", "0");
            result.put("message", "没有登录");
            return result;
        }

        String kna = juejinuser.getKnapsack();
        String[] knas = kna.split(",");

        for( int i = 0;i<knas.length;i++ ){
            if( knas[i].equals("0") ){
                result.put("status", "0");
                result.put("message", "英雄卡尚未集齐");
                return result;
            }
        }

        StringBuilder knasBuilder = new StringBuilder();
        for( int i = 0;i<knas.length;i++ ){
            Integer tmp = Integer.parseInt( knas[i] );
            tmp--;
            knasBuilder.append(tmp);
            if( (knas.length-1)!=i ){
                knasBuilder.append(",");
            }
        }

        juejinuser.setKnapsack( knasBuilder.toString() );
        juejinuser.setCoin( juejinuser.getCoin() + 1880 );
        juejinuser.setMoney( juejinuser.getMoney() + 1880/juejinuser.getRatio() );
        testService.updateUser( juejinuser );
        // 增加历史记录

        KnaHistory knaHistory = new KnaHistory();
        knaHistory.setUserid( juejinuser.getId() );
        knaHistory.setCreatetime( System.currentTimeMillis()/1000 + "" );
        knaHistory.setGetcoin( 1880 );
        knaHistory.setGetmoney( 1880/juejinuser.getRatio() );
        baseService.update( knaHistory );


        result.put("status", "1");
        result.put("coin", "1880");
        result.put("message", "success");



        return result;
    }

}